<template>
  <div class="map-viewer row bg-center"
       :class="{'page-bar': !fullscreen && $q.screen.gt.md && !staticMap, 'iframe-default': !fullscreen, 'iframe-fullscreen': fullscreen}"
       :style="{height}">
    <!--<iframe :src="iframeUrl" height="100%" width="100%" frameborder="0">-->
    <!--</iframe>-->
    <div class="bg-white"
         :class="{'crosshair': commentAdding, 'no-pointer-events': this.$q.platform.has.touch && staticMap}"
         :id="mapContainer"
         style="position: absolute;right:0;bottom: 0;top:0;left:0">
    </div>
    <div v-if="!staticMap" style="position: absolute;left:0;bottom: 0" class="q-mb-sm q-ml-sm">
      <q-btn class="button-tag" color="grey-9" @click="startAddComment">添加评论</q-btn>
      <q-btn class="button-tag" color="grey-9" @click="commentVisible = !commentVisible">{{ commentVisible ? '隐藏' : '显示'
        }}评论
      </q-btn>
    </div>
    <div v-if="!staticMap" style="position: absolute;right:0;bottom: 0" class="q-mb-sm q-mr-sm">
      <a target="_blank" :href="'/map/'+ map.id + '/?static=0'">
        <q-btn class="button-tag" color="grey-9">新窗口打开</q-btn>
      </a>
      <q-btn class="button-tag" color="grey-9" @click="fullscreen = !fullscreen">全屏</q-btn>
    </div>
    <a-dialog v-if="addCommentDialog" v-model="addCommentDialog" title="添加评论">
      <a-text-input title="添加" @submit="addComment" @close="addCommentDialog = false" :loading="loading"></a-text-input>
    </a-dialog>
    <a-dialog v-if="dialogComment" v-model="dialogComment" icon="comment" @close="reply = []" title="评论">
      <q-list separator no-border>
        <a-comment-box :comment="dialogComment" :index="dialogComment.id" @reply="replyComment"></a-comment-box>
        <a-comment-box v-for="item in reply" :key="item.id" :comment="item" :index="item.id"
                       @reply="replyComment"></a-comment-box>
      </q-list>
    </a-dialog>
  </div>
</template>

<script>
  import { AgeeyeMapViewer } from '../../maptalks/map'
  import { uid } from 'quasar'

  export default {
    name: 'aMapViewer',
    props: {
      map: {
        type: Object,
        required: true
      },
      height: {
        type: String,
        required: false,
        default: '60vh'
      },
      staticMap: {
        type: Boolean,
        required: false,
        default: false
      },
      comment: {
        type: Object,
        required: false
      }
    },
    data () {
      return {
        mapContainer: uid(),
        loading: false,
        fullscreen: false,
        commentAdding: false,
        addCommentDialog: false,
        showCommentDialog: false,
        commentVisible: true,
        commentCoordinate: null,
        comments: {},
        dialogComment: null,
        reply: []
      }
    },
    mounted () {
      if (this.comment) {
        // console.log('init')
        if (this.$store.state.pageMapData) {
          this.initMapContainer(this.$store.state.pageMapData)
        } else {
          this.$root.$on('mapDownloaded', (data) => {
            this.initMapContainer(data)
          })
        }
      } else {
        this.$store.commit('setPageMapData', null)
        this.initMapContainer()
      }
    },
    destroyed () {
      this.$mapViewer.map.remove()
      this.$mapViewer = null
    },
    computed: {},
    watch: {
      commentAdding (adding) {
        if (adding) {
          this.$mapViewer.map.setCursor('crosshair')
        } else {
          this.$mapViewer.map.resetCursor()
        }
      },
      commentVisible (visible) {
        if (visible) {
          this.$mapViewer.commentLayer.show()
        } else {
          this.$mapViewer.commentLayer.hide()
        }
      },
      fullscreen (fullscreen) {
        const element = document.getElementById('q-app')

        if (fullscreen === true) {
          element.className = 'app-fullscreen'
        } else {
          element.className = ''
        }
      }
    },
    methods: {
      async initMapContainer (mapData) {
        if (!mapData) {
          const { status, data } = await this.getRequest({
            api: 'https://ageeye-mapjson.oss-cn-hangzhou.aliyuncs.com/' + this.map.file
          })

          if (status !== 200) {
            this.notify('error', '加载地图失败，请刷新重试。')
            return
          }
          this.$store.commit('setPageMapData', data)
          setTimeout(() => {
            this.$root.$emit('mapDownloaded', data)
          }, 1000)

          mapData = data
        }

        const options = {}

        if (this.staticMap) {
          // options.zoomable = false
          // options.draggable = false

          if (this.$q.platform.has.touch) {
            options.zoomable = false
            options.draggable = false
          }

          const zoomRange = mapData.maxZoom - mapData.minZoom

          if (zoomRange <= 2) {
            options.zoom = mapData.maxZoom
          } else if (zoomRange <= 3) {
            options.zoom = mapData.maxZoom - 1
          } else {
            options.zoom = mapData.maxZoom - 2
          }
        }

        if (this.comment && this.comment.lat !== null && this.comment.lng !== null) {
          options.center = [this.comment.lng, this.comment.lat]
          options.zoomInCenter = true
        }

        this.$mapViewer = new AgeeyeMapViewer(this.mapContainer, mapData, options)
        this.$mapViewer.map.on({
          extentClick: this.onMapClick
        })

        this.$mapViewer.commentLayer.on({
          commentClick: this.onCommentClick
        })

        if (this.staticMap) {
          this.$mapViewer.commentLayer.setComments([this.comment])
        } else {
          this.getComments()
        }
      },
      onMapClick (event) {
        if (!this.commentAdding) {
          return false
        }
        this.commentCoordinate = event.coordinate
        this.addCommentDialog = true
        this.commentAdding = false
      },
      onCommentClick (event) {
        const id = event.id
        this.dialogComment = this.comments[id]
      },
      startAddComment () {
        if (!this.auth) {
          this.$router.push('/login/')
          return
        }
        this.notify('info', '请点击地图添加评论')
        this.commentAdding = true
      },
      async addComment (content) {
        const { status, data } = await this.postRequest({
          api: '/api/map/{id}/comment/',
          id: this.map.id,
          data: {
            content,
            lng: this.commentCoordinate.x,
            lat: this.commentCoordinate.y
          }
        })

        if (status === 200) {
          this.notify('success', '添加评论成功')
        } else {
          this.notify('success', '添加评论失败，请稍后重试')
        }

        this.$set(this.comments, data.id, data)
        this.$mapViewer.commentLayer.addComment(data)
        this.addCommentDialog = false
      },
      async replyComment (event) {
        const { content, parentId } = event

        const { status, data } = await this.postRequest({
          api: '/api/map/{id}/comment/',
          id: this.map.id,
          data: {
            parent: parentId,
            content
          }
        })

        if (status === 200) {
          this.reply.push(data)
          this.$root.$emit('toggleReplyInput', false)
        } else {
          this.notify('error', '添加评论失败，请稍后重试')
        }
      },
      async getComments () {
        const extent = this.$mapViewer.map.getMaxExtent()

        const { status, data } = await this.getQuerySet({
          api: '/api/comments/geo_query/',
          limit: 200,
          params: {
            id: this.map.id,
            x_min: extent.xmin,
            y_min: extent.ymin,
            x_max: extent.xmax,
            y_max: extent.ymax,
            type: 'map'
          }
        })

        if (status === 200) {
          const comments = data.results
          this.$mapViewer.commentLayer.setComments(comments)

          const commentsIndex = {}
          comments.forEach(comment => {
            commentsIndex[comment.id] = comment
          })

          this.comments = commentsIndex
        }
      }
    }
  }
</script>

<style lang="stylus">
  .map-viewer
    .crosshair
      cursor crosshair !important
    .maptalks-zoom-zoomin, .maptalks-zoom-zoomout
      display block
      background-color #424242
      color white
      padding 4px 8px
      //font-size
      width 32px !important
      border-radius 2px
      margin-bottom 10px
</style>
